package edu.whu.demo.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration // 声明这是一个配置类
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true) // 启用全局方法安全，允许pre-post请求验证
public class SecurityConfig {
    @Autowired // 自动注入JWT过滤器Bean
    JwtRequestFilter jwtRequestFilter;

    @Bean // 定义一个Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.cors(); // 开启跨域支持
        http.csrf().disable(); // 关闭CSRF过滤器

        // 配置HTTP请求的授权规则
        http.authorizeRequests((requests) -> requests
                        .antMatchers("/authenticate/login").permitAll() // login接口直接放行，否则无法访问
                        .anyRequest().authenticated()) // 其他接口需要认证
                .formLogin(Customizer.withDefaults()); // 配置表单登录功能，使用Spring Security的默认设置

        // 将jwtRequestFilter过滤器添加到UsernamePasswordAuthenticationFilter之前
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
        return http.build();
    }

    @Bean // 定义一个Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(); // 使用BCrypt加密算法
    }
}